package com.example.ceshi;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ceshi.Bean.NowUserData;
import com.example.ceshi.SQLite.MySQLiteOpenHelper;
import com.example.ceshi.utils.ImageUtil;

import org.apache.commons.collections.list.CursorableLinkedList;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class UserDetails extends AppCompatActivity {

    public static final int REQUEST_CODE_TAKE = 1;
    public static final int REQUEST_CODE_CHOOSE = 0;
    private ImageView touxiang;
    private TextView showName;
    private TextView username;
    private TextView shoucang;
    private TextView sex;
    private TextView title;
    private TextView nowdata;
    private TextView forupdate;
    private TextView noupdate;
    private Uri imageUri;
    private MySQLiteOpenHelper mySQLiteOpenHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_details);
        mySQLiteOpenHelper=new MySQLiteOpenHelper(UserDetails.this);
        touxiang = findViewById(R.id.touxiang);
        showName = findViewById(R.id.showname);
        username = findViewById(R.id.username);
        shoucang = findViewById(R.id.shoucang);
        sex = findViewById(R.id.sex);


        if (NowUserData.imgPath.equals("")) {
            touxiang.setImageResource(R.drawable.ic_touxiang);
        } else {
            touxiang.setImageBitmap(ImageUtil.base64ToImage(NowUserData.imgPath));
        }
        showName.setText(NowUserData.showName);
        username.setText(NowUserData.username);
        shoucang.setText(String.valueOf(NowUserData.maxNum));
        if (NowUserData.sex == 1) {
            sex.setText("男");
        } else {
            sex.setText("女");
        }

        findViewById(R.id.changetouxiang).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                if (ContextCompat.checkSelfPermission(UserDetails.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                    //进行拍照
                    doTake();


                } else {
                    //申请权限
                    ActivityCompat.requestPermissions(UserDetails.this, new String[]{Manifest.permission.CAMERA}, 1);
                }



                return true;
            }
        });

        findViewById(R.id.changetouxiang).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(UserDetails.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    //打开相册
                    openAlbum();


                } else {
                    //去申请权限
                    ActivityCompat.requestPermissions(UserDetails.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
                }




            }
        });

        findViewById(R.id.bigsex).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupMenu popupMenu = new PopupMenu(UserDetails.this, view);

                popupMenu.inflate(R.menu.menu_sex);
                popupMenu.show();
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem menuItem) {
                        int id = menuItem.getItemId();
                        long id2;
                        switch (id) {
                            case R.id.sex_man:
                                menuItem.setChecked(true);
                                NowUserData.sex = 1;
                                sex.setText("男");
                                id2= mySQLiteOpenHelper.updateUserDate();
                                if(id2!=-1){
                                    Toast.makeText(UserDetails.this, "修改成功", Toast.LENGTH_LONG).show();
                                }else{
                                    Toast.makeText(UserDetails.this, "修改失败", Toast.LENGTH_LONG).show();
                                }
                                break;
                            case R.id.sex_woman:
                                menuItem.setChecked(true);
                                NowUserData.sex = 0;
                                sex.setText("女");
                                id2= mySQLiteOpenHelper.updateUserDate();
                                if(id2!=-1){
                                    Toast.makeText(UserDetails.this, "修改成功", Toast.LENGTH_LONG).show();
                                }else{
                                    Toast.makeText(UserDetails.this, "修改失败", Toast.LENGTH_LONG).show();
                                }
                                break;
                        }
                        return true;
                    }
                });
            }
        });


        findViewById(R.id.nowname).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog dialog = new Dialog(UserDetails.this);
                View inflate = getLayoutInflater().inflate(R.layout.forupdatedetail, null);
                dialog.setContentView(inflate);

                title = dialog.findViewById(R.id.update_title);
                nowdata = dialog.findViewById(R.id.nowdate);
                forupdate = dialog.findViewById(R.id.forupdate);
                noupdate = dialog.findViewById(R.id.noupdate);

                title.setText("修改昵称");


                forupdate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String data = String.valueOf(nowdata.getText());
                        if (data.equals("")) {
                            Toast.makeText(UserDetails.this, "请输入内容", Toast.LENGTH_LONG).show();
                        } else {
                            NowUserData.showName = data;
                            showName.setText(data);
                            dialog.dismiss();
                            //进行数据库操作
                            long id= mySQLiteOpenHelper.updateUserDate();
                            if(id!=-1){
                                Toast.makeText(UserDetails.this, "修改成功", Toast.LENGTH_LONG).show();
                            }else{
                                Toast.makeText(UserDetails.this, "修改失败", Toast.LENGTH_LONG).show();
                            }
                        }


                    }
                });

                noupdate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });


                dialog.show();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                doTake();
            } else {
                Toast.makeText(UserDetails.this, "你没有获得需要的权限", Toast.LENGTH_LONG).show();
            }
        } else if (requestCode == 0) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openAlbum();
            } else {
                Toast.makeText(UserDetails.this, "你没有获得需要的权限", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void doTake() {
        File imageTemp = new File(getExternalCacheDir(), "imageOut.jpeg");
        if (imageTemp.exists()) {
            imageTemp.delete();
        }

        try {
            imageTemp.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (Build.VERSION.SDK_INT > 24) {
            imageUri = FileProvider.getUriForFile(UserDetails.this, "com.example.ceshi.UserDetails", imageTemp);
        } else {
            imageUri = Uri.fromFile(imageTemp);
        }
        Intent intent = new Intent();
        intent.setAction("android.media.action.IMAGE_CAPTURE");

        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        startActivityForResult(intent, REQUEST_CODE_TAKE);


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_TAKE) {
            if (resultCode == RESULT_OK) {
                try {

                    InputStream inputStream = getContentResolver().openInputStream(imageUri);
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                    touxiang.setImageBitmap(bitmap);

                    String imageToBase64 = ImageUtil.imageToBase64(bitmap);
                    NowUserData.imgPath = imageToBase64;
                    mySQLiteOpenHelper.updateUserDate();

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        } else if (requestCode == REQUEST_CODE_CHOOSE) {
            if (Build.VERSION.SDK_INT < 19) {
                handleImageBeforeApi19(data);
            } else {
                handleImageOnApi19(data);
            }
        }
    }

    @TargetApi(19)
    private void handleImageOnApi19(Intent data) {
        if (data!= null) {


            String imagePath = null;
            Uri uri = data.getData();
            if (DocumentsContract.isDocumentUri(UserDetails.this, uri)) {
                String documentId = DocumentsContract.getDocumentId(uri);

                if (TextUtils.equals(uri.getAuthority(), "com.android.providers.media.documents")) {
                    String id = documentId.split(":")[1];
                    String selection = MediaStore.Images.Media._ID + "=" + id;
                    imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);

                } else if (TextUtils.equals(uri.getAuthority(), "com.android.providers.downloads.documents")) {
                    if (documentId != null && documentId.startsWith("msf:")) {
                        resolveMSFContent(uri, documentId);
                        return;
                    }

                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                    imagePath = getImagePath(contentUri, null);
                }
            } else if ("content".equalsIgnoreCase(uri.getScheme())) {
                imagePath = getImagePath(uri, null);
            } else if ("file".equalsIgnoreCase(uri.getScheme())) {
                imagePath = uri.getPath();
            }


            displayImage(imagePath);




        }
    }

    private void resolveMSFContent(Uri uri, String documentId) {
        File file = new File(getCacheDir(), "temp_file" + getContentResolver().getType(uri).split("/")[1]);

        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);

            OutputStream outputStream = new FileOutputStream(file);

            byte[] buffer = new byte[4 * 1024];

            int read;
            while ((read = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, read);
            }

            outputStream.flush();

            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            touxiang.setImageBitmap(bitmap);
            NowUserData.imgPath = ImageUtil.imageToBase64(bitmap);
            mySQLiteOpenHelper.updateUserDate();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void handleImageBeforeApi19(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }

        return path;
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);

            touxiang.setImageBitmap(bitmap);
            NowUserData.imgPath = ImageUtil.imageToBase64(bitmap);
            mySQLiteOpenHelper.updateUserDate();

        }
    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_CODE_CHOOSE);
    }
}